package com.jiyun.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiyun.common.R;
import com.jiyun.entity.Log;
import com.jiyun.entity.LogDTO;
import com.jiyun.service.ILogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  控制层
 * </p>
 *
 * @author 聪哥哥
 * @since 2023-03-10
 */
@RestController
@RequestMapping("/log")
public class LogController {

    @Autowired
    ILogService logService;
    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("findLogById")
    public List<LogDTO> findLogById(Integer tid){
        return logService.findLogById(tid);
    }

    /**
     * 添加接口
     */
    @RequestMapping("/add")
    public R addLog(@RequestBody Log log, @CookieValue(value = "uid") String uid) {

        Boolean flag = redisTemplate.hasKey("user:" + uid);
        if (flag) {
            log.setUid(Integer.parseInt(uid));
            log.setTime(LocalDateTime.now());
            logService.save(log);
            return R.success("添加成功！");
        }else{
            return R.error("请登录！");
        }
    }

    /**
     * 修改接口
     */
    @RequestMapping("/update")
    public void updateLog(@RequestBody Log log){
        logService.updateById(log);
    }

    /**
     * 单个删除接口
     */
    @RequestMapping("/deleteOne")
    public void deleteOne(@RequestParam Integer id){
        logService.removeById(id);
    }

    /**
     * 批量删除接口
     * 前台ajax参数ids传入示例：1,2,3  (英文逗号分隔的字符串)
     */
    @RequestMapping("/deleteBatch")
    public void deleteBatch(@RequestParam List<Integer> ids){
        logService.removeByIds(ids);
    }

    /**
     * 根据id查询实体接口
     */
    @RequestMapping("/findById")
    public Log findById(@RequestParam Integer id){
        return logService.getById(id);
    }

    /**
     * 查询所有接口
     */
    @RequestMapping("/findAll")
    public List<Log> findAll(){
        return logService.list();
    }

    /**
     * 分页查询接口
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     */
    @RequestMapping("/findPage")
    public Page<Log> findPage(@RequestParam Integer page,@RequestParam Integer pageSize){
        Page<Log> logPage = new Page<>(page, pageSize);
        return logService.page(logPage);
    }

}
